package br.com.pmz.utilidades.util.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author tcs001
 */
public final class HibernateUtil {

    /**
     * Construtor privado para classes utilit&aacute;rias.
     */
    private HibernateUtil() {
    }

    /**
     * Objeto que implementa um factory de sess&atilde;o.
     */
    private static SessionFactory sessionFactory;

    static {
        try {

            sessionFactory = new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * Retorna uma instancia de sess&atilde;o atrav&eacute;s da factory.
     * @return Objeto de f&aacute;brica de sess&atilde;o.
     */
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                sessionFactory = new AnnotationConfiguration().configure()
                        .buildSessionFactory();
            } catch (Throwable ex) {
                System.err.println("Initial SessionFactory creation failed."
                        + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
        return sessionFactory;
    }

    /**
     * Abre a sess&atilde;o.
     *
     * @return Objeto Session aberto
     */
    public static Session getSession() {
        return sessionFactory.openSession();
    }

}
